package com.exigenservices.practice.roadcompanion.server.dao;

import com.exigenservices.practice.roadcompanion.server.entity.User;
import com.exigenservices.practice.roadcompanion.server.entity.UserInfo;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.springframework.stereotype.Repository;

import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * Created with IntelliJ IDEA.
 * User: Konstantin
 * Date: 11.07.13
 * Time: 15:05
 * To change this template use File | Settings | File Templates.
 */

@Repository
public class UserInfoDAOimpl implements UserInfoDAO {

    @PersistenceContext(unitName = "userinfo")
    private EntityManager entityManager;
    private static Logger LOGGER = Logger.getLogger(UserInfoDAOimpl.class.getName());

    public UserInfoDAOimpl(EntityManager entityManager){
          this.entityManager= entityManager;
    }
    @Override
    @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
    public void createUserInfo(UserInfo userInfo) throws Exception{
        try{
            entityManager.persist(userInfo);
        } catch (HibernateException e){
            LOGGER.error("UserInfoDAOimpl::Could not create User Info:: ",e);
           // throw new Exception("Could not create User Info. " + e.getMessage());
        }
    }

    @Override
    @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
    public void updateUserInfo(UserInfo userInfo) throws Exception{
        try {
            UserInfo uI = entityManager.find(UserInfo.class, userInfo);
            uI = userInfo;
        } catch (HibernateException e) {
            LOGGER.error("UserInfoDAOimpl::Could not update User Info:: ",e);
            //throw new Exception("Could not update User Info. " + e.getMessage());
        }
    }

    @Override
    @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
    public void deleteUserInfo(UserInfo userInfo) throws Exception{
        try {
            entityManager.remove(userInfo);
        } catch (HibernateException e) {
            LOGGER.error("UserInfoDAOimpl::Could not delete User Info:: ",e);
            //throw new Exception("Could not delete User Info. " + e.getMessage());
        }
    }

    @Override
    @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
    public UserInfo getUserInfo(User user) throws Exception {
        try{
            UserInfo info = entityManager.find(UserInfo.class, user.getID());
            return info;
        } catch(HibernateException e){
            LOGGER.error("UserInfoDAOimpl::Could not get User Info:: ",e);
            throw new Exception(("Could not get user " + e.getMessage()));
        }
    }
}

